package com.naiterui.ehp.bs.agent.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.naiterui.ehp.bp.support.exception.BaseExceptionCodes;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bs.agent.util.ConstantUtil;
import com.naiterui.ehp.bs.agent.websocket.WebsocketApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.naiterui.common.repository.page.PageParamVO;
import com.naiterui.common.repository.page.PageVO;
import com.naiterui.ehp.bs.agent.entity.AgNoticeMessage;
import com.naiterui.ehp.bs.agent.repository.IAgNoticeMessageRepository;
import com.naiterui.ehp.bs.agent.service.INoticeService;
import com.naiterui.ehp.bs.agent.vo.NoticeItemVO;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yiren
 * @since 2022/2/16
 */
@Slf4j
@Service
public class NoticeServiceImpl implements INoticeService {
	@Autowired
	private IAgNoticeMessageRepository agNoticeMessageRepository;
	@Autowired
	private WebsocketApi websocketApi;

	@Override
	public PageVO<NoticeItemVO> findNoticePage(Long agentId, PageParamVO pageParamVO) {
		Pageable pageable = pageParamVO.getPageable(Sort.by(Sort.Direction.DESC, "releaseTime"));
		Page<AgNoticeMessage> dbPage = agNoticeMessageRepository.findByAgentIdOrTypeAndStatus(agentId, AgNoticeMessage.TYPE_NOTICE_SYS, AgNoticeMessage.STATUS_RELEASE, pageable);
		List<NoticeItemVO> resultList = dbPage.getContent().stream().map(NoticeItemVO::of).collect(Collectors.toList());
		return PageVO.newBuilder()
				.result(resultList)
				.totalCount((int)dbPage.getTotalElements())
            .pageNo(pageParamVO.getPage()).pageSize(pageParamVO.getNum())
				.build();
	}

	@Override
	public void sendSingleMessage(String type, String agentId, String info) throws BusinessException {
		JSONObject jsonObject = JSONUtil.parseObj(info);
		String title = jsonObject.getStr("title");
		String content = jsonObject.getStr("content");
		Long time = jsonObject.getLong("time");
		if (time == null || StringUtils.isAnyEmpty(agentId, title, content, type)){
			log.error("sendSingleMessage参数异常 agentId:{}, type:{}, title:{}, content:{}, time:{}", agentId, type, title, content, time);
			throw new BusinessException(BaseExceptionCodes.PARAM_ERROR);
		}
		Integer typeCode = ConstantUtil.noticeTypeMap.get(type);
		if (typeCode != null) {
			Date messageTime = new Date(time);
			AgNoticeMessage message = new AgNoticeMessage();
			message.setType(ConstantUtil.noticeTypeMap.get(type));
			message.setAgentId(Long.valueOf(agentId));
			message.setStatus(AgNoticeMessage.STATUS_RELEASE);
			message.setContent(content);
			message.setTitle(title);
			message.setReleaseBy("sys");
			message.setReleaseTime(messageTime);
			message.setDelFlag(AgNoticeMessage.DEL_FLAG_NO);
			message.setSendStatus(AgNoticeMessage.SEND_STATUS_YES);
			agNoticeMessageRepository.save(message);
		}
		jsonObject.set("type", type);
		websocketApi.sendMessage(agentId, jsonObject.toString());
	}

	@Override
	public void sendBatchMessage(String type, String info) throws BusinessException {
		JSONObject jsonObject = JSONUtil.parseObj(info);
		String title = jsonObject.getStr("title");
		String content = jsonObject.getStr("content");
		Long time = jsonObject.getLong("time");
		if (time == null || StringUtils.isAnyEmpty(title, content, type)){
			log.error("sendBatchMessage参数异常 type:{}, title:{}, content:{}, time:{}", type, title, content, time);
			throw new BusinessException(BaseExceptionCodes.PARAM_ERROR);
		}
		jsonObject.set("type", type);
		websocketApi.sendMessage(jsonObject.toString());
	}

	@Override
	public NoticeItemVO getLastNotice(Long agentId) {
		Pageable pageable = PageRequest.of(0, 1, Sort.by(Sort.Direction.DESC, "releaseTime"));
		Page<AgNoticeMessage> dbPage = agNoticeMessageRepository.findByAgentIdOrTypeAndStatus(agentId, AgNoticeMessage.TYPE_NOTICE_SYS, AgNoticeMessage.STATUS_RELEASE, pageable);
		List<AgNoticeMessage> dbList = dbPage.getContent();
		if (dbList.size() > 0) {
			return NoticeItemVO.of(dbList.get(0));
		}
		return NoticeItemVO.builder().build();
	}
}
